package com.bnyy.medicalHousekeeper.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;

import androidx.multidex.MultiDex;
import androidx.multidex.MultiDexApplication;

import com.blankj.utilcode.util.Utils;
import com.bnyy.common.bean.UserInfo;
import com.bnyy.medicalHousekeeper.BuildConfig;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.UserInfoManager;
import com.bnyy.medicalHousekeeper.activity.LoginActivity;
import com.bnyy.medicalHousekeeper.activity.SplashActivity;
import com.bnyy.medicalHousekeeper.bean.User;
import com.bnyy.medicalHousekeeper.request.RequestManager;
import com.bnyy.common.Constant;
import com.bnyy.gbp.permission.PermissionHelper;
import com.google.gson.Gson;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshFooter;
import com.scwang.smart.refresh.layout.api.RefreshHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshFooterCreator;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshHeaderCreator;
import com.tencent.bugly.crashreport.CrashReport;

import org.xutils.x;

import java.util.ArrayList;

public class App extends MultiDexApplication {

    private static User user;
    private static int currentLoginUserId;
    private static Context context;
    private static int roleId = -1;

    public static ArrayList<Activity> activities = new ArrayList<>();
    public static Activity currentActivity;

    public static Context getInstance() {
        return context;
    }

    // public static ArrayList<Activity> activities = new ArrayList<>();
    // static 代码段可以防止内存泄露
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(com.bnyy.gbp.R.color.gray_background, R.color.gray_text);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
//        super.attachBaseContext(newContext);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Logger.addLogAdapter(new AndroidLogAdapter());
        MultiDex.install(this);
        x.Ext.init(this);
        x.Ext.setDebug(BuildConfig.DEBUG);
        UserInfoManager.getInstance().init(this);
        PermissionHelper.init(this);
        // 极光别名
        // bnyy_user_{user_id} ：用户端
        // bnyy_server_{user_id}：医护端
        // bnyy_server_diy_{user_id}：医护定制版
//        JPushUPSManager.registerToken(this, "20cfee97094ad2f849d35812", null, "", new UPSRegisterCallBack() {
//            @Override
//            public void onResult(TokenResult tokenResult) {
//                Log.e("TokenResult", "code = " + tokenResult.getReturnCode() + "  token = " + tokenResult.getToken() + "  actionType = " + tokenResult.getActionType());
//            }
//        });

        context = this;
        RequestManager.getInstance().init(this);
        CrashReport.initCrashReport(getApplicationContext(), "bcb5629939", false);
        Utils.init(this);

        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                if (activity instanceof BaseActivity) {
                    activities.add(activity);
                }
            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {
                currentActivity = activity;
            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                activities.remove(activity);
            }
        });
    }

    public static void setUser(User user) {
        Log.e("setUser", new Gson().toJson(user));
        UserInfoManager.getInstance().setUser(user);
        App.user = user;
        UserInfo userInfo = user.getUserInfo();
        currentLoginUserId = userInfo.getId();
        if (userInfo.getRoles().size() > 0) {
            if (userInfo.getRoles().size() > 0) {
                roleId = userInfo.getRoles().get(0).getId();
            }
        }

//        String alias = String.format(Constant.JPush.ALIAS, user.getUserInfo().getId());
//        Log.e("alias", alias);
//        JPushInterface.setAlias(context, 0, alias);
    }

    public static int getRoleId() {
        return roleId;
    }

    public static void setRoleId(int roleId) {
        App.roleId = roleId;
//        EventBus.getDefault().post(new EventBusData(Constant.EventBusTag.CHANGE_ROLE));
    }

    public static Activity getCurrentActivity() {
        return currentActivity;
    }

    public static ArrayList<Activity> getActivities() {
        return activities;
    }

    public static int getCurrentLoginUserId() {
        return currentLoginUserId;
    }

    public static User getUser() {
        return user;
    }


    public static void restart() {
        for (Activity activity : activities) {
            activity.finish();
        }
        Intent intent = new Intent(context, SplashActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static void loginInvalid() {
        currentLoginUserId = -1;
        roleId = -1;
        RequestManager.setToken("");
        stopAllActivity();
        user = null;

        Intent intent = new Intent(context, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static Context getContext() {
        return context;
    }

    public static void stopAllActivity() {
        for (int i = activities.size() - 1; i >= 0; i--) {
            activities.get(i).finish();
        }
    }
}


















